

Ext.namespace('PetClinic'); 
 
 

PetClinic.util = function() {

	// Private Variables for the module. Not accessible from outside

 	// do NOT access DOM from here; elements don't exist yet
 
	// private functions
	
	
	
    // public space
    return {        
    
	    // public properties, e.g. strings to translate


        // public methods
        
        /**
         * Takes an Ext.data.Record and turns it into a nested  object
         **/
	 	serialiseRecordToJSON:function(record) {
	 	
	 	}    
    }
}();
 
 
PetClinic.app = function() {
 	    // do NOT access DOM from here; elements don't exist yet
 
	// Private Variables for the module. Not accessible from outside
 	
    var vetStore = new Ext.data.Store({
    	proxy : new Ext.data.DWRProxy(DwrClinic.getVets,[]),
    	reader : new Ext.data.DwrDataReader({
    	id:'id',    	
       	totalProperty:'totalRecords',
    	fields: ['id','displayableName','address','city']}) 
	});     
	
    var specialtyStore = new Ext.data.Store({
    	proxy : new Ext.data.DWRProxy(DwrClinic.getSpecialties,[]),
    	reader : new Ext.data.DwrDataReader({
    	id:'id',
       	totalProperty:'totalRecords',
    	fields: ['id','name']}) 
	});     
	
    var petTypeStore = new Ext.data.Store({
    	proxy : new Ext.data.DWRProxy(DwrClinic.getPetTypes,[]),
    	reader : new Ext.data.DwrDataReader({
    	id:'id',
    	totalProperty:'totalRecords',
    	fields: ['id','name']}) 
	});     
	
    var ownerStore = new Ext.data.Store({
    	proxy : new Ext.data.DWRProxy(DwrClinic.findOwners),
    	reader : new Ext.data.DwrDataReader({
    	id:'id',
    	totalProperty:'totalRecords',
    	fields: ['id','displayableName','address','city']})
	});     
    var visitStore = new Ext.data.GroupingStore({
    	proxy : new Ext.data.DWRProxy(DwrClinic.findVisitsPaged, ['startDate','endDate','start','limit']),
        sortInfo:{field: 'date', direction: "ASC"},
      // remoteSort:true,
    	reader : new Ext.data.DwrDataReader({
    	id:'id',
    	root:'data',
    	totalProperty:'totalResults',
    	fields: ['id','pet.name','pet.owner.displayableName','vet.displayableName','vet.id',
    			{name:'date',type:'date'},'description']}) 
	});     
	
	var tabPanel=null; 
	
	// private functions
 	var getTabPanel=function() {
 		if(tabPanel===null) {
 			tabPanel=Ext.getCmp('mainTabPanel');
 		}
 		return tabPanel;
 	}
	
	
    // public space
    return {        
    
	    // public properties, e.g. strings to translate


        // public methods
    
	 addVisitForm :function(formId,visitId) {
	 
		var tabPanel = getTabPanel();
		// check if the form is already loaded 
		var existingForm = tabPanel.findById(formId);
		if(existingForm!==null) {
	  		tabPanel.setActiveTab(existingForm);
	  		return existingForm;
	   	}
		 var visitForm = new Ext.form.FormPanel( {
	        id: formId,
	        frame: true,
	        closable:true,
	        labelAlign: 'left',
	        title: 'Visit Details',
	        defaultType: 'textfield',
	        items: [{xtype:'hidden',
	        		name:'id'
	        },{ xtype:'combo',
	            	store:vetStore,
	            	 editable: false,
					 triggerAction: 'all',
					 emptyText:'Choose...',
					 selectOnFocus:true,
					 forceSelection : true,
	            	displayField:'displayableName',
	            	valueField:'id',
	                fieldLabel: 'Vet',
	                hiddenName: 'vet.id',
					 listeners: {
					   beforerender: function(combo){
					   }
					 }
	            },{ xtype:'combo',
	            	 editable: true,
	            	 typeAhead:true,
	            	 minChars:1,
					 triggerAction: 'all',
					 emptyText:'Choose...',
					 selectOnFocus:true,
					 forceSelection : true,
					 store: new Ext.data.Store({
				    	proxy : new Ext.data.DWRProxy(DwrClinic.findOwners,['query']),
				    	reader : new Ext.data.DwrDataReader({
				    	id:'id',
				    	totalProperty:'totalRecords',
				    	fields: ['id','displayableName','address','city']})
					}),
	            	displayField:'displayableName',
	            	valueField:'id',
	                fieldLabel: 'Owner',
	                name: 'owner.id',
	                hiddenName: 'owner.id',
					 listeners: {
					   beforerender: function(combo){
					   }, 
					   select: function(combo,record,index) {
					   	// we've selected an owner, now we need to populate the Pet selection combo
					   	// - the pets are a property of the JSON Owner object we pulled down from DWR
							var thePets = record.json.pets;			
							var petCombo = visitForm.form.findField('pet.id');
							petCombo.clearValue();
							petCombo.store.loadData(thePets);
							//petCombo.select(petCombo.store.getAt(0).id);
							petCombo.enable();	   
					   }
	 				 }
	            },{ xtype:'combo',
	            	 editable: true,
	            	 typeAhead:true,
	            	 minChars:1,
	            	 disabled:true,
					 triggerAction: 'all',
					 mode:'local',
					 emptyText:'Choose...',
					 selectOnFocus:true,
					 forceSelection : true,
					 store: new Ext.data.SimpleStore({
					 	id:'id',
				    	fields: ['id','name']
					}),
	            	displayField:'name',
	            	valueField:'id',
	                fieldLabel: 'Pet',
	                name: 'pet.name',
	                hiddenName: 'pet.id',
					 listeners: {
	  				 }
	            },{
	                fieldLabel: 'Date',
	                 xtype:'xdatetime',
	                name: 'date',
	                timeFormat:'H:i',
	                timeConfig: {
	                     altFormats:'H:i',
		                minValue: '8:00am',
		                maxValue: '6:00pm',
	                    allowBlank:false    
	                },
	                dateFormat:'d/n/Y',
	                dateConfig: {
	                     altFormats:'Y-m-d|Y-n-d',
	                    allowBlank:false,    
		                timeWidth:50
	                }
	            },{
	                fieldLabel: 'Description',
	                name: 'description',
	                xtype:'htmleditor'
	            }
	        ],
	
	        buttons: [{
	            text: 'Save',handler:function() {
	            	var values = visitForm.form.getValues();
	            	// transform the flat values to nested objects
	            	var petId = values['pet.id'];
	            	var vetId = values['vet.id'];
	            	var ownerId = values['owner.id'];
	            	values.pet={};
	            	values.pet.id=petId;
	            	values.vet={};
	            	values.vet.id=vetId;
	            	values.owner={};
	            	values.owner.id=ownerId;
	            	Ext.Msg.alert('Details',Ext.util.JSON.encode(values));
	            	return;
					DwrClinic.storeVisit(values, {callback:function(visit) { 
					}});
	            }
	        },{
	            text: 'Cancel',handler:function() {
	            	Ext.getCmp('mainTabPanel').remove(visitForm);
	            }
	        }]
	 	
	   });
	   
		// load the owner into the form if one was provided
		if(visitId !==null) {
			DwrClinic.loadVisit(visitId, {callback:function(visit) {
				visitForm.form.setValues(visit); 
				visitForm.setTitle("Visit ID:"+visit.id);
			}});
		} else {
	   		// create a new visit form 
	  		visitForm.setTitle('New Visit');
		}
		// add it to the main tab panel
		tabPanel.add(visitForm);
		tabPanel.setActiveTab(visitForm);
	
	   return visitForm;
},


////////////////
////////////////
 // creates a new owner form
 addOwnerForm:function(formId, ownerId) {

	var tabPanel = getTabPanel();
	// check if the form is already loaded 
	var existingForm = tabPanel.findById(formId);
	if(existingForm!==null) {
  		tabPanel.setActiveTab(existingForm);
  		return existingForm;
   	}
	 var ownerForm = new Ext.form.FormPanel( {
        id: formId,
        frame: true,
        labelAlign: 'left',
        title: 'Loading...',
        defaultType: 'textfield',
        closable:true,
        items: [{xtype:'hidden',
        		name:'id'
        },{ name:'firstName', fieldLabel:'First Name'
        },{ name:'lastName', fieldLabel:'Last Name'
        },{ name:'address', fieldLabel:'Address',width:300
        },{ name:'city', fieldLabel:'City'
        },{ name:'telephone', fieldLabel:'Telephone'
        },{name: 'notes',fieldLabel: 'Notes' 
				        //,xtype:'textarea'
				        ,xtype:'htmleditor'
            }        
       ],

        buttons: [{
            text: 'Save',handler:function() {
            	var values = ownerForm.form.getValues();
            	DwrClinic.storeOwner(values,function() {
            		// remove the tab
	            	tabPanel.remove(ownerForm);
	            	// refresh the tree
	            	var tree = Ext.getCmp('ownerTree');
            		tree.getLoader().load(tree.getRootNode());
            	});
            //	Ext.Msg.alert('Details',Ext.util.JSON.encode(values));
            }
        },{
            text: 'Cancel',handler:function() {
            	Ext.getCmp('mainTabPanel').remove(ownerForm);
            }
        }]
 	
 });
	// load the owner into the form if one was provided
	if(ownerId !==null) {
		DwrClinic.loadOwner(ownerId, {callback:function(owner) {
			ownerForm.form.setValues(owner); 
			ownerForm.setTitle(owner.displayableName);
		}});
	} else {
   		// create a new owner form 
  		ownerForm.setTitle('New Owner');
	}
	// add it to the main tab panel
	tabPanel.add(ownerForm);
	tabPanel.setActiveTab(ownerForm);
	
 return ownerForm;
},

/////////////////
////////////////

 // creates a new Vet form
addVetForm:function(formId, vetId) {
	var tabPanel = getTabPanel();
	// check if the form is already loaded 
	var existingForm = tabPanel.findById(formId);
	if(existingForm!==null) {
  		tabPanel.setActiveTab(existingForm);
  		return existingForm;
   	}
 var vetForm = new Ext.form.FormPanel( {
        id: formId,
        frame: true,
        closable:true,
        labelAlign: 'left',
        title: 'Vet Details',
        defaultType: 'textfield',
        items: [{xtype:'hidden',
        		name:'id'
        },{ name:'firstName', fieldLabel:'First Name'
        },{ name:'lastName', fieldLabel:'Last Name'
        },{ name:'address', fieldLabel:'Address'
        },{ name:'city', fieldLabel:'City'
        },{ name:'telephone', fieldLabel:'Telephone'
            },
        { 
					xtype:"multiselect",
					name:"specialties",
					id:formId+'specSelector',
					fieldLabel:"Specialties",
					dataFields:["id", "name"],
					store:specialtyStore,
					msWidth:250,
					msHeight:200,
					valueField:"id",
					displayField:"name",
					imagePath:"../script/ext/plugins/multiselect",
					//switchToFrom:true,
					toLegend:"Selected",
					fromLegend:"Available",
					toTBar:[{
						text:"Clear",
						handler:function(){
							var i=vetForm.getForm().findField("specialties");
							i.reset.call(i);
						}
					}]
             } 
        ],

        buttons: [{
            text: 'Save',handler:function() {
            	var values = vetForm.form.getValues();
            	//Ext.Msg.alert('Details',Ext.util.JSON.encode(values));
            	var specialtiesStr =values.specialties; 
            	// split the specialties to a string 
            	var specIds = specialtiesStr.split(','); 
            	var specs = [];
            	// store them back as an array of objects
            	for(var i =0; i<specIds.length;i++) {
	            	specs.push({id:specIds[i]});
	            }
	            values.specialties=specs;
            	DwrClinic.storeVet(values,function() {
            		// remove the tab
	            	getTabPanel().remove(vetForm);
	            	// refresh the tree
	            	var tree = Ext.getCmp('vetTree');
            		tree.getLoader().load(tree.getRootNode());
            	});
            }
        },{
            text: 'Cancel',handler:function() {
            	getTabPanel().remove(vetForm);
            }
        }]
 	
 
	 });
 
	// load the owner into the form if one was provided
	if(vetId !==null) {
		DwrClinic.loadVet(vetId, {callback:function(vet) {
			// get the specialties 
			var specialties = vetForm.form.findField(formId+'specSelector');
			var specs = [];
            	for(var i =0; i<vet.specialties.length;i++) {
	            	specs.push(vet.specialties[i].id);
	            }
			vetForm.form.setValues(vet); 
			if(specs.length>0) {
				specialties.setValue(specs.join(','));
			}
            //	Ext.Msg.alert('Details',Ext.util.JSON.encode(vet));
			vetForm.setTitle(vet.displayableName);
		}});
	} else {
   		// create a new owner form 
  		vetForm.setTitle('New Vet');
	}
	// add it to the main tab panel
	tabPanel.add(vetForm);
	tabPanel.setActiveTab(vetForm);
	
 return vetForm;
},

/////////////////
 // creates a new pet form
 addPetForm:function(formId, petId) {
 	var tabPanel = getTabPanel();
	// check if the form is already loaded 
	var existingForm = tabPanel.findById(formId);
	if(existingForm!==null) {
  		tabPanel.setActiveTab(existingForm);
  		return existingForm;
   	}
	 var petForm = new Ext.form.FormPanel( {
        id: formId,
        frame: true,
        labelAlign: 'left',
        title: 'Loading...',
        defaultType: 'textfield',
        closable:true,
        items: [{xtype:'hidden',
        		name:'id'
        },{ name:'name', fieldLabel:'Name',allowBlank:false
        },{ name:'birthDate', fieldLabel:'Birth Date',xtype: 'datefield',allowBlank:false
        },{xtype:'combo',
            	 editable: true,
            	 typeAhead:true,
            	 id:formId+'pOwner',
            	 minChars:1,
				 triggerAction: 'all',
				 emptyText:'Choose...',
				 selectOnFocus:true,
				 forceSelection : true,
				 store: new Ext.data.Store({
			    	proxy : new Ext.data.DWRProxy(DwrClinic.findOwners,['query']),
			    	reader : new Ext.data.DwrDataReader({
			    	id:'id',
			    	totalProperty:'totalRecords',
			    	fields: ['id','displayableName','address','city']})
				}),
            	displayField:'displayableName',
            	valueField:'id',
                fieldLabel: 'Owner',
                name: 'owner.id',
                hiddenName: 'owner.id',
				 listeners: {
				   beforerender: function(combo){
				    // debugger;
				    	combo.setValue(combo.store.getAt(0).id); // FINAL LINE
				     // MyCombo.setValue(MyCombo.store.collect('id', true)[0]); // this line isn't rapid
				   }, 
				   select: function(combo,record,index) {
				   	// we've selected an owner, now we need to populate the Pet selection combo
				   	// - the pets are a property of the JSON Owner object we pulled down from DWR
						var thePets = record.json.pets;			
						var petCombo = Ext.getCmp('vPetIdCombo');
						petCombo.clearValue();
						petCombo.store.loadData(thePets);
						//petCombo.select(petCombo.store.getAt(0).id);
						petCombo.enable();	   
				   }
 				 }
        },{xtype:'combo',
            	 editable: true,
            	 typeAhead:true,
            	 id:formId+'pType',
            	 minChars:1,
				 triggerAction: 'all',
				 emptyText:'Choose...',
				 selectOnFocus:true,
				 forceSelection : true,
				 store: petTypeStore,
				 displayField:'name',
            	valueField:'id',
                fieldLabel: 'Type',
                name: 'type.id',
                hiddenName: 'type.id',
				 listeners: {
				   beforerender: function(combo){
				   // debugger;
//				    	combo.setValue(combo.store.getAt(0).id); // FINAL LINE
				     // MyCombo.setValue(MyCombo.store.collect('id', true)[0]); // this line isn't rapid
				   }
  				 }
        
//        },{ name:'type.id', xtype:'combo'  '
            }
        ],

        buttons: [{
            text: 'Save',handler:function() {
            	var values = petForm.form.getValues(false);
            	// fetch the birthdate separately as form.getValues() doesn't return Date() objects for date fields
            	var birthDate = petForm.form.findField('birthDate').getValue();
            	values.birthDate=birthDate;
            	DwrClinic.storePet(values,function() {
            		// remove the tab
	            	getTabPanel().remove(petForm);
	            	// refresh the tree
	            	var tree = Ext.getCmp('ownerTree');
            		tree.getLoader().load(tree.getRootNode());
            	});
            //	Ext.Msg.alert('Details',Ext.util.JSON.encode(values));
            }
        },{
            text: 'Cancel',handler:function() {
            	getTabPanel().remove(petForm);
            }
        }]
 	
 });
	// load the owner into the form if one was provided
	if(petId !==null) {
		DwrClinic.loadPet(petId, {callback:function(pet) {
			petForm.form.setValues(pet); 
			// load the owner id correctly 
			var ownerCombo = petForm.form.findField(formId+'pOwner');
		//	var owner =ownerCombo.store.getById(pet.owner.id);
			// load the owner id correctly 
			var typeCombo = petForm.form.findField(formId+'pType');
			var type = typeCombo.store.getById(pet.type.id);
 			typeCombo.select(type);
			//debugger;
//			ownerCombo.select();
			petForm.setTitle(pet.name);
		}});
	} else {
   		// create a new owner form 
  		petForm.setTitle('New Owner');
	}
	// add it to the main tab panel
	tabPanel.add(petForm);
	tabPanel.setActiveTab(petForm);
	
	
 return petForm;
},
        init : function(){ // Priviledged method. Can be called from outside
            // Here comes the initialisation code
		    Ext.QuickTips.init();

			/// load up the stores		
			////////////////
				dwr.engine.beginBatch();
				vetStore.load();
				specialtyStore.load();
				petTypeStore.load();
				dwr.engine.endBatch();	
			////////////////////////	

////////////////

    var ownerGrid = new Ext.grid.GridPanel({
        id:'ownerGrid',
        columns: [
            {id:'id',header: "Id", width:10, sortable: false, dataIndex: 'id',hidden:true},
            {header: "Name", width: 290, sortable: true, dataIndex: 'displayableName'},
            {header: "Address", width: 290, sortable: true, dataIndex: 'address'},
            {header: "City", width: 290, sortable: true, dataIndex: 'city'}
        ], 
        stripeRows: true,
        title:'Owners',
        tbar:["Name",new Ext.form.TextField({
        	id:'ownerNameSearch'
        }),
        "-", {xtype:'tbbutton',text:'Search',icon:'../images/find.png', cls:'x-btn-text-icon',
        	handler:function() {
        		var searchName = Ext.getCmp('ownerNameSearch').getValue();
				Ext.getCmp('ownerGrid').getStore().load({params:[searchName]});
        	}
        }
        ],
        store: ownerStore,
            	listeners:[{loadexception: function() {
		   Ext.Msg.alert('error');    	
    	}}],
    	    	stateful:true,
           sm: new Ext.grid.RowSelectionModel({
	                singleSelect: true,
	                listeners: {
	                    rowselect: function(selModel,rowIndex,record) {
	                    }
	                }
	            })    	
    });


/////////////////

	var visitGridMenu = new Ext.menu.Menu({
		 items:[{icon:'../images/application_form_edit.png', 
			text:'Edit', handler:function() {
			
			
			}},
			{icon:'../images/application_form_delete.png', 
			text:'Delete', handler:function() {
					visitGridMenu.hide();
					// Show a dialog using config options:
					Ext.Msg.show({
					   title:'Confirm Deletion',
					   msg: 'Are you sure you want to delete this visit?',
					   buttons: Ext.Msg.YESNO,
					   fn: function(result) { 
					    	if(result=="yes") {
							   	Ext.Msg.alert('Not implemented...', 'Coming soon...');
						   	}
					   },
					   icon: Ext.MessageBox.WARNING
					});
			
			}}
		]
	});
	
    var visitGrid = new Ext.grid.GridPanel({
        id:'visitGrid',
              columns: [
            {id:'id',header: "Id", width:10, sortable: false, dataIndex: 'id',hidden:true},
            {header: "Date", width: 110, sortable: true, renderer:Ext.util.Format.dateRenderer('d/m/Y'), dataIndex: 'date'},
            {header: "Pet Name", width: 290, sortable: true, dataIndex: 'pet.name'},
            {header: "Owner Name", width: 290, sortable: true, dataIndex: 'pet.owner.displayableName'},
            {header: "Vet Name", width: 290, sortable: true, dataIndex: 'vet.displayableName'},
            {header: "Description", width: 290, sortable: true, dataIndex: 'description'}
        ],
    view: new Ext.grid.GroupingView({
        forceFit:true,
        // custom grouping text template to display the number of items per group
        groupTextTpl: '{text} ({[values.rs.length]} {[values.rs.length > 1 ? "Items" : "Item"]})'
    }),
                tbar: ["From",
				 new Ext.form.DateField({
                                    fieldLabel: 'Start Date',
                                    id:'sd',
                                    name: 'sd',
                                    value:'01/01/70',
                                    allowBlank:false
                                }),
                                "-","To",
                                 new Ext.form.DateField({
                                    fieldLabel: 'End Date',
                                    id:'ed',
                                    name: 'ed',
                                    value:'03/03/08',
                                    allowBlank:false
                                }),                
                "-",
			{xtype:'tbbutton',text:'Search',icon:'../images/find.png', cls:'x-btn-text-icon',
               handler: function() {  
                 var startdate = Ext.getCmp('sd').getValue();
                 var enddate = Ext.getCmp('ed').getValue();
               visitGrid.getStore().load(
               			{params:{start:0,limit:25,startDate:startdate,endDate:enddate}});
			 }},
            "-",
            { text: "Add New", icon:'../images/application_form_add.png', cls:'x-btn-text-icon',
            tooltip:"Add a new Visit",
            handler: function() {
			        	var formId = 'visitForm_'+new Date().getTime();
 	            		  // check if the form is already loaded 
			        		// create a new visit form 
			        		PetClinic.app.addVisitForm(formId,null);
			        	 }},
            "-",
            { text: "Edit", disabled:true, id:'editVisitButton', icon:'../images/application_form_edit.png', cls:'x-btn-text-icon',
            tooltip:"Edit Selected Visit",
            handler: function() {
            			var selModel = visitGrid.getSelectionModel();
            			var thisRow = selModel.getSelected(); 
            			if(!thisRow || !thisRow.id) {
	            			return;
            			}
            			var rowId = thisRow.id; 
            			
			        	var formId = 'visitForm_'+rowId;
 	            		  // check if the form is already loaded 
			        		// create a new visit form 
		        		PetClinic.app.addVisitForm(formId,rowId);
        	}},
            "->" ,
            { text: "Clear", handler: function() { visitGrid.getStore().removeAll(); }}
		],    
    	stateful:true,
        loadMask: true,
        stripeRows: true,
        title:'Visits',
        store: visitStore,
        bbar : new Ext.ux.FilteredPagingToolbar({store:visitStore,
	        pageSize:25, displayInfo:true
        
        }),
        listeners:{rowdblclick:function(grid,rowIndex,evt) {
        		var row = grid.getView().getRow(rowIndex);
        	},
	        rowcontextmenu:function(grid, rowIndex,evt) {
	        	evt.preventDefault();
	        	visitGridMenu.showAt(evt.getXY());
	        }
        
        },
        sm: new Ext.grid.RowSelectionModel({
	                singleSelect: true,
	                listeners: {
	                    rowselect: function(selModel,rowIndex,record) {
		                    Ext.getCmp('editVisitButton').enable();
	                    },
	                    rowdeselect: function(selModel,rowIndex,record) {
		                    Ext.getCmp('editVisitButton').disable();
	                    }
	                }
	      })    	
        
    });
    


////////////////


/////////////////

var ownerTree =  {
	        title: 'Owners',
	        id:'ownerTree',
	        xtype: 'treepanel',
//	        region:'west',
			width:200,
	        autoScroll: true,
	        loader: new Ext.tree.DwrTreeLoader({
		        loadFunction: DwrClinic.findOwners,
		        nameField:'displayableName',
		        loadParam:"",
		        blankLoadParam:true,
		        childProperty:'pets',idPrefix:'owner'
	        }),
	        root: new Ext.tree.AsyncTreeNode({
	        	id:'root',
	        	text:'Root',
	        	expanded:false
	        }),
	        rootVisible: false,
	        listeners: {
	            dblclick: function(n) {
	            	// get the id 
	            	var id = n.attributes.id; 
	            	var idParts = id.split('_'); 
	            	
		        	var tabPanel = Ext.getCmp('mainTabPanel');
		        	var formId,existingForm;
	            	if(idParts[0]=='owner') {
		        		 formId = 'ownerForm_'+idParts[1];
		        		// create a new owner form 
		        		 PetClinic.app.addOwnerForm(formId,idParts[1]);
	            	} else if(idParts[0]=='pets') {
                  		 formId = 'petForm_'+idParts[1];
	            		// check if the form is already loaded 
	            		 existingForm = tabPanel.findById(formId);
	            		if(existingForm!==null) {
			        		tabPanel.setActiveTab(existingForm);
			        	}else {
			        		// create a new owner form 
			        		var newForm = newPetForm(formId,idParts[1]);
			        		// add it to the main tab panel
			        		tabPanel.add(newForm);
			        		tabPanel.setActiveTab(newForm);
			        	}
	            	
	            	}
	//            		                Ext.Msg.alert('Navigation Tree Click', 'You clicked: "' + n.attributes.id + '"');
	            	
	            },
	            beforerender:function(tree) {
	            // create a sorter
	            	new Ext.tree.TreeSorter(tree);
	            	// load the tree
					 tree.getRootNode().expand();
	            }
	        }, 
	        tbar:[ 
	        	{text:'Add Owner',icon:'../images/user_add.png', 
	        	cls:'x-btn-text-icon',
	        	handler: function() {
	        		// create a new owner form 
	        		 PetClinic.app.addOwnerForm(new Date().getTime(),null);
	        	}
	        	},
	        	{text:'Add Pet',icon:'../images/bug_add.png', 
	        	cls:'x-btn-text-icon',disabled:true},"->", {text:'Refresh', handler:function() {
	        		var tree = Ext.getCmp('ownerTree');
	        		tree.getLoader().load(tree.getRootNode());
	        	}}
	        ]
	    };

////////////////
/////////////////

var vetTree =  {
	        title: 'Vets',
	        id:'vetTree',
	        xtype: 'treepanel',
	        autoScroll: true,
	//        width:200,
//	        region:'west',
	        loader: new Ext.tree.DwrTreeLoader({
		        loadFunction: DwrClinic.getVets, 
		        loadParam:null,
		        nameField:'displayableName', idPrefix:'vet'
	        }),
	        root: new Ext.tree.AsyncTreeNode({
	        	text:'Root',id:'vetRoot',
	        	expanded:false
	        }),
	        rootVisible: false,
	        listeners: {
	            dblclick: function(n) {
	            	// get the id 
	            	var id = n.attributes.id; 
	            	var idParts = id.split('_'); 
	            	
		        	var tabPanel = Ext.getCmp('mainTabPanel');
		        	var formId,existingForm;
	            	if(idParts[0]=='vet') {
		        		 formId = 'vetForm_'+idParts[1];
	        		// create a new vet form 
	        		 PetClinic.app.addVetForm(formId,idParts[1]);
	            	}
	            },
	            beforerender:function(tree) {
	            // create a sorter
	            	new Ext.tree.TreeSorter(tree);
	            	// load the tree
					 tree.getRootNode().expand();
	            }
	        }, 
	        tbar:[ 
	        	{text:'Add Vet',icon:'../images/user_add.png', 
	        	cls:'x-btn-text-icon',
	        	handler: function() {
	        		// create a new vet form 
	        		 PetClinic.app.addVetForm(new Date().getTime(),null);
	        	  }
	        	},"->", {text:'Refresh', handler:function() {
	        		var tree = Ext.getCmp('vetTree');
	        		tree.getLoader().load(tree.getRootNode());
	        	}}
	         ]
	    };

////////////////
////////////////




////////////////
var leftPanel ={
			id:'leftPanel',
			xtype:'tabpanel',
	        region: 'west',
	        title:'Chooser',
	        collapsible : true,
			width:240,
	        split: true,
		//	layout:'accordion',
			layoutConfig:{
		        titleCollapse: false,
		        animate: true,
		        activeOnTop: false						
			},
		items:[ownerTree,vetTree]
};
 
var viewport=	new Ext.Viewport({
	    layout: 'border',
	    defaults: {
	        activeItem: 0
	    },
	    items: [{
	        region: 'north',
	        html: '<h1 class="x-panel-header">Petstore</h1>',
	        autoHeight: true,
	        border: false,
	        margins: '0 0 5 0'
	    }, leftPanel,{
	        region: 'center',
	        xtype: 'tabpanel',
	        id: 'mainTabPanel',
	        enableTabScroll:9,
	        items: [{
	            title: 'Welcome',
	            autoLoad:{url:'welcome.jsp'}
//	            html: 'The first tab\'s content. Others may be added dynamically'
	        },ownerGrid,visitGrid
	        
	        ]
	    }, {
	        region: 'south',
	        title: 'Information',
	        collapsible: true,
	        html: 'Information goes here',
	        split: true,
	        height: 50,
	        minHeight: 50
	    }]
	});

		Ext.get('loading').hide(true);
		
            
        } 
    }
  
}();

///////////////
    /*
    Ext.state.Manager.setProvider(new Ext.state.DwrStateProvider({
    	getFunction:DwrExtStateManager.getPreference,
	    setFunction:DwrExtStateManager.setPreference,
    	clearFunction:DwrExtStateManager.clearPreference,
    	bulkLoadFunction:DwrExtStateManager.getAllPreferences,
    }));
    Ext.state.Manager.setProvider(new Ext.state.LoggingStateProvider()); 
	*/
